<template>
  <div class="app-container">
    <el-input v-model="search.keyword" placeholder="keyword " style="width:300px" />
    <el-button type="primary" @click="getRoles">Search</el-button>
    <el-button type="primary" @click="handleAddRole">Add</el-button>

    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border empty-text="Can't find record in table">
      <!-- <el-table-column align="center" label="NO" width="100">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column> -->
      <el-table-column align="header-center" label="Client Name" width="250">
        <template slot-scope="scope">
          <span class="link-type" @click="handleInfo(scope)">
            {{ scope.row.hotel_name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="header-center" label="Location Address" min-width="250">
        <template slot-scope="scope">{{ scope.row.address }}</template>
      </el-table-column>
      <el-table-column align="center" label="Action" width="80">
        <template slot-scope="scope">
          <el-col :span="12">
            <el-link style="font-size:18px;" class="el-icon-edit icon-class" @click="handleEdit(scope)" />
          </el-col>
          <el-col :span="12">
            <el-link style="font-size:18px;" class="el-icon-delete icon-class" @click="handleDelete(scope)" />
          </el-col>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :current-page="search.page"
      :page-size="search.per_page"
      style="margin-top:10px; float:right"
      @current-change="getPageList"
    />

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? 'Edit Client' : 'New Client'"
    >
      <el-form ref="hotelForm" :model="hotel" :rules="rules" label-width="150px" label-position="left">
        <el-form-item label="Client Name" prop="hotel_name">
          <el-input v-model="hotel.hotel_name" placeholder="Client Name" />
        </el-form-item>
        <el-form-item label="Location Address" prop="address">
          <el-input
            v-model="hotel.address"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="Location Address"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="confirmRole">Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { baseAPI } from '@/utils/request'
import { getHotels, saveHotels, deleteHotel } from '@/api/hotel'

const defaultHotel = {
  id: 0,
  hotel_name: '',
  address: '',
  en_flag: ''
}

export default {
  data() {
    return {
      hotel: Object.assign({}, defaultHotel),
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      rules: {
        hotel_name: [
          { required: true, message: 'Please enter a name', trigger: 'blur' }
        ],
        address: [
          { required: true, message: 'Please enter the address', trigger: 'blur' }
        ]
      },
      search: {
        keyword: '',
        page: 1,
        per_page: 10
      },
      total: 10
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  watch: {
    dialogVisible(newValue, oldValue) {
      // 清空验证
      if (this.$refs['hotelForm']) this.$refs['hotelForm'].clearValidate()
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getRoutes()
    this.getRoles()
  },
  methods: {
    async getRoutes() {
      const res = await baseAPI.get('user/role/routes')
      this.serviceRoutes = res
      this.routes = res
    },
    async getRoles() {
      const res = await getHotels(this.search)
      this.rolesList = res.data
      this.total = res.total
      this.search.page = parseInt(res.current_page)
      this.search.per_page = res.per_page
    },
    async getPageList(value) {
      this.search.page = value
      const res = await getHotels(this.search)
      this.rolesList = res.data
      this.total = res.total
      this.search.page = parseInt(res.current_page)
      this.search.per_page = res.per_page
    },
    handleAddRole() {
      this.hotel = Object.assign({}, defaultHotel)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.hotel.id = scope.row.id
      this.hotel.hotel_name = scope.row.hotel_name
      this.hotel.address = scope.row.address
    },
    handleInfo(scope) {
      this.$router.push({
        path: '/client/detail',
        query: { id: scope.row.id, name: scope.row.hotel_name, address: scope.row.address }
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('Confirm to remove the role?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      })
        .then(async() => {
          await deleteHotel({ id: row.id })
          this.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: 'Delete succed!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    async confirmRole() {
      this.$refs.hotelForm.validate(async valid => {
        if (valid) {
          await saveHotels(this.hotel).then(async() => {
            const { hotel_name, address } = this.hotel
            this.dialogVisible = false
            this.$notify({
              title: 'Success',
              dangerouslyUseHTMLString: true,
              message: `
                  <div>Hotel Name: ${hotel_name}</div>
                  <div>Location Address: ${address}</div>
                `,
              type: 'success'
            })

            // 更新列表
            await this.getRoles()
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
